/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useEffect } from 'react';
import { Row, Col, TreeSelect, Space } from 'antd';
import { getDepartments, getAllUsers } from '@/services/admin/editMenu';
import { ManagerInfo } from '@/pages/admin/menu/index.d';
import styles from './authSelect.less';

const AuthSelect: React.FC<any> = ({ handleSelect, userData }) => {
  const [departmentList, setDepartmentList] = useState<any[]>([]);
  const [isTeam, setIsTeam] = useState<boolean>(true);
  const [userInfo, setUserInfo] = useState<ManagerInfo>({});

  const getUserList = async (department: any) => {
    const { data = [] } = await getAllUsers({ department_id: department.id });
    const list = departmentList.filter((item: any) => {
      if (item.id == department.id) {
        item.children = data.map((item1: any) => {
          return Object.assign(
            {},
            {
              isLeaf: true,
              title: item1.name,
              value: item1.id,
              department_list: item1.department_list,
            },
          );
        });
        if (item.children.length) {
          item.disabled = false;
        }
      }
      return item;
    });
    setDepartmentList(list);
  };

  const getDepartmentList = async () => {
    const { data = [] } = await getDepartments({});
    const department = data.map((item: any) => {
      return Object.assign(
        {},
        {
          id: item.id,
          isLeaf: false,
          title: item.name,
          value: item.id + '99999999',
          disabled: true,
        },
      );
    });
    setDepartmentList(department);
  };

  const handelChange = (values: any) => {
    handleSelect(values);
  };

  useEffect(() => {
    getDepartmentList();
    if (userData) {
      setUserInfo(userData);
      handleSelect(userData.id);
      setIsTeam(false);
    }
  }, [userData]);

  return (
    <Row>
      <Col style={{ marginRight: 5, display: 'flex', alignItems: 'center' }}>授权对象:</Col>
      <Col span={22}>
        {isTeam ? (
          <TreeSelect
            className={styles.authSelect}
            showSearch={false}
            treeData={departmentList}
            treeCheckable={true}
            showCheckedStrategy='SHOW_CHILD'
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            onChange={handelChange}
            loadData={getUserList}
          />
        ) : (
          <Space>
            {userInfo.department_list.map((iten: any) => iten.name).join('、')}｜{userInfo.name}
          </Space>
        )}
      </Col>
    </Row>
  );
};

export default AuthSelect;
